import Joi from 'joi';
import {Context} from 'koa';

export const validateRequestBody = <T>(schema: Joi.Schema) => {
    return function (target: T, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = async function (ctx: Context) {
            try {
                const validatedData = await schema.validateAsync(ctx.request.body);
                ctx.state.validatedData = validatedData;
                return originalMethod.call(this, ctx);
            } catch (error) {
                ctx.throw(400, error as string);
            }
        };

        return descriptor;
    };
};

export const validateRequestQuery = <T>(schema: Joi.Schema) => {
    return function (target: T, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = async function (ctx: Context) {
            try {
                const validatedData = await schema.validateAsync(ctx.request.query);
                ctx.state.validatedData = validatedData;
                return originalMethod.call(this, ctx);
            } catch (error) {
                ctx.throw(400, error as string);
            }
        };

        return descriptor;
    };
};

export const validateRequestFile = <T>(schema: Joi.Schema) => {
    return function (target: T, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = async function (ctx: Context) {
            try {
                const validatedData = await schema.validateAsync(ctx.request.files);
                ctx.state.validatedData = validatedData;
                return originalMethod.call(this, ctx);
            } catch (error) {
                ctx.throw(400, error as string);
            }
        };

        return descriptor;
    };
};

